import {login, getUserInfo} from '@/api/user'
import router from '@/router/index'
import {ElLoading, ElMessage} from 'element-plus'
import {defineStore} from 'pinia'
import {ref, computed, watch} from 'vue'
import {useRouterStore} from './router'

export const useUserStore = defineStore('user', () => {
    const loadingInstance = ref(null)

    const userInfo = ref({
        defaultRouter: 'dashboard',
        sideMode: 'dark',
        activeColor: 'var(--el-color-primary)',
        baseColor: '#888787'
    })

    const token = ref(window.sessionStorage.getItem('token') || '')
    const setUserInfo = (val) => {
        userInfo.value = val
        userInfo.defaultRouter = "dashboard";
    }

    const setToken = (val) => {
        token.value = val
    }

    const NeedInit = () => {
        token.value = ''
        window.sessionStorage.removeItem('token')
        sessionStorage.clear()
        router.push({name: 'Init', replace: true})
    }

    const ResetUserInfo = async () => {
        userInfo.value = {}
        await GetUserInfo()
    }
    /* 获取用户信息*/
    const GetUserInfo = async () => {
        const res = await getUserInfo()
        if (res.code === 0) {
            setUserInfo(res.data)
        }
        return userInfo.value
    }
    /* 登录*/
    const LoginIn = async (loginInfo) => {
        loadingInstance.value = ElLoading.service({
            fullscreen: true,
            text: '登录中，请稍候...',
        })
        try {
            const res = await login(loginInfo)
            if (res.code === 0) {
                setToken(res.data)
                const routerStore = useRouterStore()
                await routerStore.SetAsyncRouter()
                const asyncRouters = routerStore.asyncRouters
                asyncRouters.forEach(asyncRouter => {
                    router.addRoute(asyncRouter)
                })

                loadingInstance.value.close()

                const isWin = ref(/windows/i.test(navigator.userAgent))
                if (isWin.value) {
                    window.localStorage.setItem('osType', 'WIN')
                } else {
                    window.localStorage.setItem('osType', 'MAC')
                }
                return true
            }
        } catch (e) {
            loadingInstance.value.close()
        }
        loadingInstance.value.close()
    }

    /* 登出*/
    const LoginOut = async () => {
        sessionStorage.clear()
        router.push({name: 'Login', replace: true})
        window.location.reload()
    }
    /* 清理数据 */
    const ClearStorage = async () => {
        token.value = ''
        sessionStorage.clear()
        localStorage.clear()
    }
    /* 设置侧边栏模式*/
    const changeSideMode = async (data) => {
        localStorage.setItem('sideMode', data)
        userInfo.value.sideMode = data
        ElMessage({
            type: 'success',
            message: '设置成功'
        })
    }

    const mode = computed(() => userInfo.value.sideMode)

    const sideMode = computed(() => {
        const side = localStorage.getItem('sideMode')
        if (side !== null) {
            userInfo.value.sideMode = side
        }
        if (userInfo.value.sideMode === 'dark') {
            return '#191a23'
        } else if (userInfo.value.sideMode === 'light') {
            return '#fff'
        } else {
            return userInfo.value.sideMode
        }
    })

    const baseColor = computed(() => {
        if (userInfo.value.sideMode === 'dark') {
            return '#fff'
        } else if (userInfo.value.sideMode === 'light') {
            return '#191a23'

        } else {
            return userInfo.value.baseColor
        }
    })
    const activeColor = computed(() => {
        return 'var(--el-color-primary)'
    })

    watch(() => token.value, () => {
        window.sessionStorage.setItem('token', token.value)
    })

    return {
        userInfo,
        token,
        NeedInit,
        ResetUserInfo,
        GetUserInfo,
        LoginIn,
        LoginOut,
        changeSideMode,
        mode,
        sideMode,
        setToken,
        baseColor,
        activeColor,
        loadingInstance,
        ClearStorage
    }
})
